/*
 * MConsultas.java
 *
 * Created on 3 de abril de 2006, 10:38 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package ig.metrica.ui.origenesdedatos.consultas;

import ig.metrica.origenesdedatos.*;
import ig.metrica.ui.ServiceLocator;
import ig.metrica.ui.interfaces.comunes.IModelo;
import ig.util.CodigoBotones;
import ig.util.NoContinuaException;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.ArrayList;
import javax.naming.NamingException;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.view.JasperViewer;
import pruebas.SourceClass;

/**
 *
 * @author jsanchez
 */
public class MConsultas implements IModelo {

    private Connection connection = null;
    private String NombreConexion;
    private String connectURL;
    private String uName;
    private String pWord;
    private String driverName;    
    private PConsultas panel = null;
    /**
     * Creates a new instance of MConsultas
     */
    private Collection COrigenesDatos = null;
    private Collection COrigenesDatosRemote = null;
    private Collection CConexiones = null;
    private Collection CEntidades = null;
    //OrigenDeDatosHome home =null;
    //ConexionHome conexionHome=null;

    public MConsultas(PConsultas panel) throws Exception {
        this.panel = panel;
    }

    public void guardar() throws NoContinuaException {
        Collection CCC = panel.getCollection();
        for (Object elem : CCC) {
            OrigenesdatosDTO TO = ((OrigenesdatosDTO) elem);
            if (((OrigenesdatosDTO) elem).getCampos().startsWith("N")) {
                try {
                    new OrigenDeDatosBean().ejbCreate(TO.getId(), TO.getEntidad(), TO.getCampos(), TO.getQuery(), TO.getIdconexion(), TO.getConsecutivo(), TO.getTipo());
                } catch (Exception ex) {
                    throw new NoContinuaException("Error tratando de grabar los Informes " + ex.toString());
                }
            } else {
                if (((OrigenesdatosDTO) elem).getCampos().startsWith("U")) {
                    try {
                        OrigenDeDatosBean origen = new OrigenDeDatosBean().ejbFindByPrimaryKey(new OrigenDeDatosPK(TO.getId()));
                        origen.setCampos("S" + TO.getCampos().substring(1, TO.getCampos().length()));
                        origen.setQuery(TO.getQuery());
                        origen.setIdConexion(TO.getIdconexion());
                        origen.setEntidad(TO.getEntidad());
                        origen.actualizarEntidad();
                    } catch (Exception ex) {
                        throw new NoContinuaException("Error tratando de grabar los Informes " + ex.toString());
                    }
                }
            }
        }
    }

    public String getNameConexion(Integer integer) {
        if (CConexiones != null) {
            for (Object elem : CConexiones) {
                try {
                    int id = Integer.valueOf(((ConexionBean) elem).getId().toString()).intValue();
                    if (id == integer) {
                        return ((ConexionBean) elem).getNombre();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        return null;
    }

    public Collection buscar() throws NoContinuaException {
        try {
            panel.clear();
            /*
             * Properties prop = new Properties(); prop.put(
             * Context.INITIAL_CONTEXT_FACTORY, IGBean.INITIAL_CONTEXT_FACTORY);
             * String Sockec = new ConexionServer().getSocketServer(); prop.put(
             * Context.PROVIDER_URL, Sockec); InitialContext ctx; ctx = new InitialContext(prop);
             */

            Collection resultado = CConexiones = new ConexionBean().ejbFindByPropiedades( "","","","","");;
            setDataConexiones(resultado);

            //home = (OrigenDeDatosHome)ctx.lookup("ig.metrica.origenesdedatos.OrigenDeDatos");
            //OrigenDeDatos origenesDatos=home.findByPrimaryKey(new OrigenDeDatosPK(1));
            COrigenesDatos = new OrigenDeDatosBean().findByAllDTO();
            setDataCBoxEntidades(COrigenesDatos);


            return COrigenesDatos;
        } catch (RemoteException ex) {
            ex.printStackTrace();
        } catch (NamingException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public Integer getConsecutivo() {
        return consecutivo;
    }
    private Collection Conexiones = new ArrayList();

    private void setDataConexiones(Collection cone) throws RemoteException {
        this.Conexiones = cone;
        for (Object elem : cone) {
            panel.addDataCBoxConexiones(((ConexionBean) elem).getNombre().trim());
        }
    }

    public void modificar() throws NoContinuaException {
    }
    OrigenesdatosDTO newOrigenesdatosDTO = null;
    boolean nuevo = false;

    public void nuevo() throws NoContinuaException {
        String NOMBRE = JOptionPane.showInputDialog("Escriba el Nombre para el nuevo Informe y/o Validaci\u00F3n:");
        if (NOMBRE != null && !NOMBRE.trim().equals("")) {
            OrigenesdatosDTO dto = new OrigenesdatosDTO();
            dto.setEntidad(NOMBRE);
            Integer id = 2001;
            for (Object elem : COrigenesDatos) {
                if (((OrigenesdatosDTO) elem).getId().equals(id)) {
                    id++;
                }
                if (NOMBRE.equals(((OrigenesdatosDTO) elem).getEntidad().trim())) {
                    throw new NoContinuaException("Ya Existe un Informe con este nombre");
                }
            }
//            dto.setId(id);
            dto.setQuery("");
            dto.setCampos("N");
            panel.addDataCBoxEntidades(dto);
            panel.mpd.setEstado(CodigoBotones.guardar + CodigoBotones.salir);
        } else {
            //panel.mpd.setEstado(CodigoBotones.modificar+CodigoBotones.salir+CodigoBotones.nuevo+CodigoBotones.eliminar);
            throw new NoContinuaException("Nada Seleccionado");
        }
    }

    public void eliminar() throws NoContinuaException {
        //OrigenDeDatosPK pk = new OrigenDeDatosPK(1);
        try {
            if ( !new OrigenDeDatosBean().eliminarConsulta(panel.getDTO().getConsecutivo()) ) {
                throw new NoContinuaException("No se pudo eliminar la Consulta por error de con la Base de Datos");
            }
        } catch (Exception ex) {
            throw new NoContinuaException(ex.getMessage()+"\n"+ex);
        }
    }

    public void salir() throws NoContinuaException {
    }

    public void imprimir() throws NoContinuaException {
    }
    Integer consecutivo = -1;

    public Object getTO() throws NoContinuaException {
        return null;
    }

    public void cancelar() throws NoContinuaException {
    }

    public void loadAtributos() throws Exception {
        String nameCombox = panel.getConexion();
        if (panel.getQuery().toUpperCase().contains("DROP") || panel.getQuery().toUpperCase().contains("DELETE") || panel.getQuery().toUpperCase().contains("TRUNCATE") || panel.getQuery().toUpperCase().contains("UPDATE")) {
            throw new Exception("DELETE, TRUNCATE, UPDATE son palabras reservadas");
        }

        /*if (conexionHome == null) {
            Properties prop = new Properties();
            prop.put(Context.INITIAL_CONTEXT_FACTORY, IGBean.INITIAL_CONTEXT_FACTORY);
            String Sockec = new ConexionServer().getSocketServer();
            prop.put(Context.PROVIDER_URL, Sockec);
            InitialContext ctx = new InitialContext(prop);
            conexionHome = (ConexionHome) ctx.lookup("ig.metrica.origenesdedatos.Conexion");
        }*/
        
        Collection resultado = new ConexionBean().ejbFindByPropiedades("", "", "", "", "");
        Iterator i = resultado.iterator();

        while (i.hasNext()) {
            ConexionBean conexion = (ConexionBean) i.next();
            if (conexion.getNombre().equals(nameCombox)) {
                setNombreConexion(conexion.getNombre().trim());
                setConnectURL(conexion.getUrl().trim());
                setUName(conexion.getUsuario().trim());
                setPWord(conexion.getPassword().trim());
                setDriverName(conexion.getDriver().trim());
                break;
            }
        }
    }


    public boolean validarConsulta(boolean isSetData) {
        //setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
        PreparedStatement preparedStatement = null;
        try {
            this.loadAtributos();
            if (!getDriverName().trim().equalsIgnoreCase("sun.jdbc.odbc.JdbcOdbcDriver")) {
                connection = getConnections(getConnectURL(), getUName(), getPWord(), getDriverName());
                preparedStatement = connection.prepareStatement(panel.getQuery());
                ResultSet RESULTADO = preparedStatement.executeQuery();
                setDataReultado(RESULTADO, isSetData);
                return true;
            } else {
                //try {
                    connection = getConnections(getConnectURL(), getUName(), getPWord(), getDriverName());
                    preparedStatement = connection.prepareStatement(panel.getQuery());
                    ResultSet RESULTADO = preparedStatement.executeQuery();
                    setDataReultado(RESULTADO, isSetData);
                    return true;
                /*} catch (Exception e) {
                    OrigenDeDatos origen = ServiceLocator.getInstancia().getOrigenDatos("MONEDASVALORES");
                    ArrayList datos = origen.obtenerDatos(panel.getQuery(), driverName, getConnectURL(), getUName(), getPWord());
                    this.setDataReultadoA(datos, isSetData);
                    return true;
//                    panel.setValidacionConsulta("Error en la validaci\u00F3n del query: "+ex.toString(),false);
//                    return false;
                }*/
            }
        } catch (Exception ex) {
            setDataReultado(null, isSetData);
            panel.setValidacionConsulta("Error en la validaci\u00F3n del query: " + ex.toString(), false);
            return false;
        } finally {
            try {
                preparedStatement.close();
            } catch (Exception e) {
            }
            try {
                connection.close();
            } catch (Exception e) {
            }
        }
    }

    private Connection getConnections(String connectURL, String uName, String pWord, String driverName) throws ClassNotFoundException, SQLException {
        try {
            Class.forName(driverName);
            Properties prop = new Properties();
            if (driverName.trim().equals("org.relique.jdbc.csv.CsvDriver")) {
                prop.put("separator", uName.trim());
                prop.put("fileExtension", pWord.trim());
            } else {
                prop.put("user", uName.trim());
                prop.put("password", pWord.trim());
            }
            return DriverManager.getConnection(connectURL, uName, pWord);
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            throw new ClassNotFoundException(ex.getMessage());
        } catch (SQLException ex) {
            throw new SQLException(ex.getMessage());
        }
    }

    private void setDataCBoxEntidades(Collection COrigenesDatos) {
        Collection C = new ArrayList();
        for (Object elem : COrigenesDatos) {
            if (((OrigenesdatosDTO) elem).getId() >= 2000 && ((OrigenesdatosDTO) elem).getId() < 3000) {
                C.add(elem);
                panel.addDataCBoxEntidades(((OrigenesdatosDTO) elem));
            }
        }
        this.COrigenesDatos = C;
    }

    private void setDataCBoxConsultas() {
    }

    private String getConsulta(int index) {
        return "NO TIENE";
    }
    String consulta = "";

    public void updateData(String quien) {
    }
    private String[] nombreCol = new String[0];

    private void setDataReultado(ResultSet RESULTADO, boolean isSetData) {
        this.dataBean = null;
        int n = 0;
        try {
            if (RESULTADO != null) {
                n = RESULTADO.getMetaData().getColumnCount();
                setNombreCol(new String[n]);
                for (int i = 1; i <= n; i++) {
                    getNombreCol()[i - 1] = RESULTADO.getMetaData().getColumnName(i);
                }
                Collection<Object[]> c = new ArrayList();
                boolean k = false;
                while (RESULTADO.next()) {
                    Object[] obj = new Object[n];
                    for (int i = 1; i <= getNombreCol().length; i++) {
                        obj[i - 1] = RESULTADO.getObject(i);
                    }
                    c.add(obj);
                    k = true;
                }
                setData(new Object[c.size()][n]);
                int i = 0;
                for (Object[] elem : c) {
                    for (int j = 0; j < n; j++) {
                        if (elem[j] == null) {
                            getData()[i][j] = "<null>";
                        } else if (elem[j].getClass().getName().equals("java.sql.Date") || elem[j].getClass().getName().equals("java.util.Date") || elem[j].getClass().getName().equals("java.sql.Timestamp")) {
                            if (!isSetData) {
                                getData()[i][j] = elem[j];
                            } else if (elem[j] instanceof java.sql.Date) {
                                getData()[i][j] = new Timestamp(((java.sql.Date) elem[j]).getTime()).toString().subSequence(0, 10);
                            } else if (elem[j] instanceof java.sql.Timestamp) {
                                getData()[i][j] = new Timestamp(((java.sql.Timestamp) elem[j]).getTime()).toString().subSequence(0, 10);
                            } else if (elem[j] instanceof java.util.Date) {
                                getData()[i][j] = new Timestamp(((java.util.Date) elem[j]).getTime()).toString().subSequence(0, 10);
                            }
                        } else {
                            getData()[i][j] = elem[j];
//                            System.out.println(elem[j].getClass().getName());
                        }
                    }
                    i++;
                }
                panel.nombreColunmas(getNombreCol());
                panel.setValidacionConsulta("Ejecuci\u00F3n de Informe exitoso " + getData().length + " Registros", true);
                if (isSetData) {
                    panel.setData(getData());
                }

            } else {
                panel.setData(null);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    SourceClass MyClase = new SourceClass();
//    private void genearClasees(String[] ){
//
//    }

    private void setDataReultadoA(ArrayList RESULTADO, boolean isSetData) {
        int n = 0;
        try {
            if (RESULTADO != null) {

                MyClase.setNombreClase("Bean");
                MyClase.setPaquete("ig.prueba");

                String[] columnas = null;
                for (Object elem : RESULTADO) {
                    if (elem instanceof String[]) {
                        columnas = (String[]) elem;
                        RESULTADO.remove(columnas);
                        break;
                    }
                }
                for (int i = 0; i < columnas.length; i++) {
                    String clase = "java.lang.String";
                    if (RESULTADO.iterator().hasNext() && ((Object[]) RESULTADO.iterator().next())[i] != null) {
                        clase = ((Object[]) RESULTADO.iterator().next())[i].getClass().getName();
                    }
                    MyClase.addAtributos(columnas[i], clase, true, "null");
                }

                MyClase.bulidClase("");

                this.nombreCol = columnas;
                n = RESULTADO.iterator().hasNext() ? ((Object[]) RESULTADO.iterator().next()).length : 0;

                Collection<Object[]> c = new ArrayList();
                Collection cD = new ArrayList();
                boolean k = false;
                Iterator Registro = RESULTADO.iterator();
                while (Registro.hasNext()) {
                    Object[] Reg = (Object[]) Registro.next();
                    Object[] obj = new Object[n];
                    for (int i = 0; i < columnas.length; i++) {
                        obj[i] = Reg[i];
                        String strTMP = columnas[i].substring(0, 1).toUpperCase() + columnas[i].substring(1, columnas[i].length());
                        Object MyObj = MyClase.getInstanciaDeLaClase();
                        MyClase.invocarMetodo(MyObj, "set" + strTMP, obj[i] != null ? obj[i] : "<null>");
                        cD.add(MyObj);
                    }
                    c.add(obj);
                    k = true;
                }
                Object[][] data = new Object[c.size()][n];
                int i = 0;
                for (Object[] elem : c) {
                    for (int j = 0; j < n; j++) {
                        if (elem[j] == null) {
                            data[i][j] = "<null>";
                        } else if (elem[j].getClass().getName().equals("java.sql.Date") || elem[j].getClass().getName().equals("java.util.Date") || elem[j].getClass().getName().equals("java.sql.Timestamp")) {
                            if (elem[j] instanceof java.sql.Date) {
                                data[i][j] = new Timestamp(((java.sql.Date) elem[j]).getTime()).toString().substring(0, 10);
                            } else if (elem[j] instanceof java.sql.Timestamp) {
                                data[i][j] = new Timestamp(((java.sql.Timestamp) elem[j]).getTime()).toString().substring(0, 10);
                            } else if (elem[j] instanceof java.util.Date) {
                                data[i][j] = new Timestamp(((java.util.Date) elem[j]).getTime()).toString().substring(0, 10);
                            }
                        } else {
                            data[i][j] = elem[j];
                        }
                    }
                    i++;
                }
                this.setData(data);
                this.dataBean = cD.toArray();
                if (isSetData) {
                    panel.nombreColunmas(columnas);
                    panel.setData(data);
                }
            } else {
                panel.setData(null);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    private Object[][] data = new Object[0][0];
    private Object[] dataBean = new Object[0];

    public Collection getConexiones() {
        return Conexiones;
    }

    public void setConexiones(Collection Conexiones) {
        this.Conexiones = Conexiones;
    }

    private String getFormato(Object[][] data, String nombre, String _class, Object obj) {
        if (data != null) {
            for (int i = 0; i < data.length; i++) {
                if (data[i][0].toString().trim().equals(nombre.trim())) {
                    return data[i][2].toString();
                }
            }
        }
        if (_class.equals("java.math.BigDecimal") && ((BigDecimal) obj).scale() > 0) {
            return ("#,##0.00");
        } else if (_class.equals("java.math.BigDecimal") && ((BigDecimal) obj).scale() == 0) {
            return ("#,##0");
        } else if (_class.equals("java.lang.Integer")) {
            return ("#,##0");
        } else if (_class.equals("java.lang.Double")) {
            return ("#,##0.00");
        } else if (_class.equals("java.util.Date")
                || _class.equals("java.sql.Timestamp")
                || _class.equals("java.sql.Date")
                || _class.equals("oracle.sql.DATE")
                || _class.equals("oracle.sql.TIMESTAMP")) {
            return ("yyyy/MM/dd");
        } else {
            JOptionPane.showMessageDialog(this.panel, "Error: Comuniquele este mensaje a:"
                    + "\nigsoporte@informaciongerencial.com"
                    + "\nClase indefinida :" + _class);
        }

        return null;
    }

    public void buildInforme(Map parametros) throws JRException, ClassNotFoundException, SQLException, IOException, NamingException {

        if (this.validarConsulta(false) && this.getData().length > 0) {

            FileReader read = new FileReader(new File("server/textField.jrxml"));
            BufferedReader br = new BufferedReader(read);
            String linea = null;
            String TextField = new String();

            /*
             * Leemos el textField
             */
            while ((linea = br.readLine()) != null) {
                TextField = TextField + linea + "\n";
            }
            read.close();
            br.close();

            read = new FileReader(new File("server/textStatic.jrxml"));
            br = new BufferedReader(read);
            linea = null;
            String TextStatic = new String();

            /*
             * Leemos el textStatic
             */
            while ((linea = br.readLine()) != null) {
                TextStatic = TextStatic + linea + "\n";
            }
            read.close();
            br.close();


            read = new FileReader(new File("server/BuilderIGMetrica.jrxml"));
            br = new BufferedReader(read);
            linea = null;
            String XML = new String();
            Object[][] _data = panel.loadDataFormato();
            /*
             * Leemos el Builder
             */
            while ((linea = br.readLine()) != null) {
                if (linea.trim().equals("<!--TEXTFIELD-->")) {
                    /*
                     * Pocesamiento de los testField
                     */
                    for (int i = 0; i < this.getNombreCol().length; i++) {
                        boolean str = false;
                        String TextFieldUpdate = TextField.replaceAll("_X_", String.valueOf(108 * i));
                        if (!this.getData()[0][i].getClass().getName().equals("java.lang.String")) {
                            String classs = this.getData()[0][i].getClass().getName();
                            TextFieldUpdate = TextFieldUpdate.replaceAll("_CLASS_", this.getData()[0][i].getClass().getName().equals("java.sql.Date") ? "java.util.Date" : this.getData()[0][i].getClass().getName());
                            TextFieldUpdate = TextFieldUpdate.replaceAll("_PATTERN_", this.getFormato(_data, this.getNombreCol()[i], this.getData()[0][i].getClass().getName(), this.getData()[0][i]));
                            TextFieldUpdate = TextFieldUpdate.replaceAll("_ALIGNMENT_", "Right");
                        } else {
                            TextFieldUpdate = TextFieldUpdate.replaceAll("_CLASS_", this.getData()[0][i].getClass().getName());
                            TextFieldUpdate = TextFieldUpdate.replaceAll("pattern=\"_PATTERN_\"", " ");
//                            TextFieldUpdate=TextFieldUpdate.replaceAll("_PATTERN_",this.getFormato(_data ,this.getNombreCol()[i],this.getData()[0][i].getClass().getName(),this.getData()[0][i]));
                            TextFieldUpdate = TextFieldUpdate.replaceAll("_ALIGNMENT_", "Left");
                        }

                        TextFieldUpdate = TextFieldUpdate.replaceAll("_VALOR_", String.valueOf(this.getNombreCol()[i]));
                        String TextFieldUpdateTMP = "";
                        if (this.getData()[0][i].getClass().getName().equals("java.lang.String")) {
                            boolean ok = false;
                            for (int j = 0; j < TextFieldUpdate.length(); j++) {
                                if (TextFieldUpdate.toCharArray()[j] == '$' || ok) {
                                    TextFieldUpdateTMP = TextFieldUpdateTMP + "\" \"+" + TextFieldUpdate.toCharArray()[j];
                                } else {
                                    TextFieldUpdateTMP = TextFieldUpdateTMP + TextFieldUpdate.toCharArray()[j];
                                }
                            }
                        }
                        XML = XML + (!TextFieldUpdateTMP.trim().equals("") ? TextFieldUpdateTMP + "\n" : TextFieldUpdate + "\n");
                    }
                    XML = XML + "<line direction=\"TopDown\">\n"
                            + "<reportElement\n"
                            + "x=\"" + 108 * this.getNombreCol().length + "\"\n"
                            + "y=\"0\"\n"
                            + "width=\"0\"\n"
                            + "height=\"16\"\n"
                            + "key=\"line-1\"/>\n"
                            + "<graphicElement stretchType=\"NoStretch\"/>\n"
                            + "</line>\n";

                } else if (linea.trim().equals("<!--TEXTSTATIC-->")) {
                    /*
                     * Pocesamiento de los testStatic
                     */
                    for (int i = 0; i < this.getNombreCol().length; i++) {
                        String TextStaticUpdate = TextStatic.replaceAll("_X_", String.valueOf(108 * i));
                        TextStaticUpdate = TextStaticUpdate.replaceAll("_TEXT_", String.valueOf(this.getNombreCol()[i]).trim().toUpperCase());
                        XML = XML + TextStaticUpdate + "\n";
                    }
                    XML = XML + "<line direction=\"TopDown\">\n"
                            + "<reportElement\n"
                            + "x=\"" + 108 * this.getNombreCol().length + "\"\n"
                            + "y=\"6\"\n"
                            + "width=\"0\"\n"
                            + "height=\"12\"\n"
                            + "key=\"line-1\"/>\n"
                            + "<graphicElement stretchType=\"NoStretch\"/>\n"
                            + "</line>\n";
                } else {
                    XML = XML + linea + "\n";
                }
            }
            read.close();
            br.close();

            //Reemplazamos el tamano de la pagina dependiendo del numero de columnas de que existan
            Integer Anchura = (this.getNombreCol().length * 108) + 60;

            Anchura = Anchura < 612 ? 612 : Anchura;
//            Anchura=130*(this.getNombreCol().length>2?this.getNombreCol().length:3);

            XML = XML.replaceAll("_WIDTH1_", Anchura.toString());
            XML = XML.replaceAll("_WIDTH2_", String.valueOf(Anchura - 60));
            XML = XML.replaceAll("_QUERY_", panel.getQuery());

            read = new FileReader(new File("server/field.jrxml"));
            br = new BufferedReader(read);
            linea = null;
            String Field = new String();

            /*
             * Leemos el field
             */
            while ((linea = br.readLine()) != null) {
                Field = Field + linea + "\n";
            }
            read.close();
            br.close();

            /*
             * Pocesamiento de los testField y field
             */
            for (int i = 0; i < this.getNombreCol().length; i++) {
                String FieldUpdate = Field.replaceAll("_CLASS_", this.getData()[0][i].getClass().getName());
                FieldUpdate = FieldUpdate.replaceAll("_NAME_", String.valueOf(this.getNombreCol()[i]));
                try {
                    XML = XML.replaceAll("<!--FIELD-->", FieldUpdate.trim());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
//            FileWriter write=new FileWriter(new File("server/tmp/BuildIGMetrica.jrxml"));
//            write.write(XML);
//            write.flush();
//            write.close();

            ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(XML.getBytes()); // par convertirlo en un InputStream           
            new TJasperViewer(arrayInputStream, dataBean == null ? getConnections(getConnectURL(), getUName(), getPWord(), getDriverName()) : null, parametros, this.panel, dataBean).start();

        } else {
            panel.setEnabledBInforme(true);
        }
    }

    class TJasperViewer extends Thread {

        Connection con;
        PConsultas panel;
        Map parametros;
        Object[] data = null;
        ByteArrayInputStream arrayInputStream = null;

        TJasperViewer(ByteArrayInputStream arrayInputStream, Connection con, Map parametros, PConsultas panel, Object[] data) {
            this.parametros = parametros;
            this.con = con;
            this.panel = panel;
            this.data = data;
            this.arrayInputStream = arrayInputStream;
        }

        @Override
        public void run() {
            try {
                //JasperReport jr = JasperCompileManager.compileReport("server/tmp/BuildIGMetrica.jrxml");
                JasperReport jr = JasperCompileManager.compileReport(arrayInputStream);
                JasperViewer viewer = null;
                if (data == null) {
                    viewer = new JasperViewer(JasperFillManager.fillReport(jr, parametros, this.con));
                } else {
                    JRBeanArrayDataSource CDataSource = new JRBeanArrayDataSource(this.data);
                    viewer = new JasperViewer(JasperFillManager.fillReport(jr, parametros, CDataSource));
                }
                panel.addPane(viewer.getContentPane());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this.panel, "Error: No se pudo generar el reporte\n" + e.toString());
            }
            panel.setEnabledBInforme(true);
        }
    }

    public String getNombreConexion() {
        return NombreConexion;
    }

    public void setNombreConexion(String NombreConexion) {
        this.NombreConexion = NombreConexion;
    }

    public String getConnectURL() {
        return connectURL;
    }

    public void setConnectURL(String connectURL) {
        this.connectURL = connectURL;
    }

    public String getUName() {
        return uName;
    }

    public void setUName(String uName) {
        this.uName = uName;
    }

    public String getPWord() {
        return pWord;
    }

    public void setPWord(String pWord) {
        this.pWord = pWord;
    }

    public String getDriverName() {
        return driverName;
    }

    public void setDriverName(String driverName) {
        this.driverName = driverName;
    }

    public Object[][] getData() {
        return data;
    }

    public void setData(Object[][] data) {
        this.data = data;
    }

    public String[] getNombreCol() {
        return nombreCol;
    }

    public void setNombreCol(String[] nombreCol) {
        this.nombreCol = nombreCol;
    }
}
